package com.wlz.dao;

import com.wlz.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * wlz
 *
 * http://bat.ke.qq.com
 * 往期视频加群:516212256 暗号:6
 */
@Repository
public class UserRepository {

    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    public Collection<User> findAll() {

        List<User> users = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<User>(User.class));
        return users;
    }

    public boolean save(User user) {
        boolean success=false;
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            PreparedStatement preparedStatement = connection.prepareStatement("insert into user(name) value(?)");
            preparedStatement.setString(1,user.getName());
            success = preparedStatement.executeUpdate()>0;
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(connection !=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}
